import React, { useEffect, useState } from 'react';
import './DataFilterModal.css';

const DataFilterModal = ({
  isOpen = false,
  onClose = () => {},
  onConfirm = () => {},
  columns = [],
  data = [],
  initialFilters = {},
  title = '筛选'
}) => {
  const [localFilters, setLocalFilters] = useState(initialFilters);

  useEffect(() => {
    if (isOpen) {
      setLocalFilters(initialFilters || {});
    }
  }, [isOpen, initialFilters]);

  if (!isOpen) return null;

  const handleChange = (key, value) => {
    setLocalFilters(prev => ({ ...prev, [key]: value }));
  };

  const handleConfirm = () => {
    onConfirm(localFilters);
    onClose();
  };

  const handleCancel = () => {
    setLocalFilters(initialFilters || {});
    onClose();
  };

  const handleOverlayClick = (e) => {
    if (e.target === e.currentTarget) {
      handleCancel();
    }
  };

  // 预设字段定义与键名
  const fieldDefs = [
    { key: 'author', label: '作者', type: 'text', placeholder: '请输入作者' },
    { key: 'authorOrder', label: '作者位次', type: 'select', options: [] },
    { key: 'keywords', label: '关键词', type: 'text', placeholder: '请输入关键词' },
    { key: 'journalName', label: '期刊名称', type: 'select', options: [] },
    { key: 'foundedDate', label: '建刊时间', type: 'date' },
    { key: 'jcrPartition', label: 'JCR分区', type: 'select', options: ['Q1','Q2','Q3','Q4'] },
    { key: 'sciPartition', label: 'SCI分区', type: 'select', options: ['一区','二区','三区','四区'] },
    { key: 'otherLevel', label: '其他等级', type: 'text', placeholder: '请输入' },
    { key: 'domain', label: '所属领域', type: 'select', options: [] },
    { key: 'impactFactor', label: '影响因子', type: 'text', placeholder: '如 >=5' },
    { key: 'citationCount', label: '被引次数', type: 'text', placeholder: '如 >=100' }
  ];

  // 根据数据聚合下拉项（如果有对应键）
  const collectUnique = (key) => {
    const set = new Set();
    (data || []).forEach(item => {
      if (item && item[key] !== undefined && item[key] !== null && item[key] !== '') {
        set.add(String(item[key]));
      }
    });
    return Array.from(set);
  };

  const fields = fieldDefs.map(def => {
    if (def.key === 'authorOrder') {
      const options = collectUnique('authorOrder');
      return { ...def, options: options.length ? options : ['第一作者','通讯作者','共同一作','其他'] };
    }
    if (def.key === 'journalName') {
      const options = collectUnique('journalName');
      return { ...def, options };
    }
    if (def.key === 'domain') {
      const options = collectUnique('domain');
      return { ...def, options };
    }
    return def;
  });

  return (
    <div className="data-filter-modal-overlay" onClick={handleOverlayClick}>
      <div className="data-filter-modal">
        <div className="data-filter-modal__header">
          <h3 className="data-filter-modal__title">{title}</h3>
        </div>

        <div className="data-filter-modal__body">
          <div className="data-filter-modal__grid">
            {fields.map((f) => (
              <div key={f.key} className="data-filter-modal__field">
                <label className="data-filter-modal__label">{f.label}</label>
                {f.type === 'select' ? (
                  <select
                    className="data-filter-modal__input"
                    value={localFilters[f.key] ?? ''}
                    onChange={(e) => handleChange(f.key, e.target.value)}
                  >
                    <option value="">全部</option>
                    {(f.options || []).map((opt) => (
                      <option key={opt} value={opt}>{opt}</option>
                    ))}
                  </select>
                ) : f.type === 'date' ? (
                  <input
                    type="date"
                    className="data-filter-modal__input"
                    value={localFilters[f.key] ?? ''}
                    onChange={(e) => handleChange(f.key, e.target.value)}
                  />
                ) : (
                  <input
                    type="text"
                    className="data-filter-modal__input"
                    placeholder={f.placeholder || '请输入'}
                    value={localFilters[f.key] ?? ''}
                    onChange={(e) => handleChange(f.key, e.target.value)}
                  />
                )}
              </div>
            ))}
          </div>
          <div className="data-filter-modal__hint">数字字段支持 &gt;、&gt;=、&lt;、&lt;=、= 前缀比较</div>
        </div>

        <div className="data-filter-modal__footer">
          <button 
            className="data-filter-modal__btn data-filter-modal__btn--confirm"
            onClick={handleConfirm}
          >
            确定
          </button>
          <button 
            className="data-filter-modal__btn data-filter-modal__btn--cancel"
            onClick={handleCancel}
          >
            取消
          </button>
        </div>
      </div>
    </div>
  );
};

export default DataFilterModal;


